package com.gemantic.task.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.gemantic.task.dto.BaseResponseVo;
import com.gemantic.task.dto.BatchUpdateDto;
import com.gemantic.task.dto.ResResult;
import com.gemantic.task.dto.TaskQueryReqDto;
import com.gemantic.task.dto.TaskQueryRespDto;
import com.gemantic.task.model.Task;
import com.gemantic.task.service.TaskService;

@RestController
@RequestMapping("/task")
public class TaskController {
    private final static String RUNNER_NAME_PREFIX = "api_task";

    @Autowired
    private TaskService taskService;


    @RequestMapping(value = "/runTask", method = RequestMethod.GET)
    public ResResult runTask(Long id) {
        String name = Thread.currentThread().getName();
        String runnerName = String.format("%s_%s", RUNNER_NAME_PREFIX, name);
        return taskService.runTask(id, runnerName);
    }

    @RequestMapping(value = "/updateTask", method = RequestMethod.POST)
    public BaseResponseVo updateTask(@RequestBody Task task) {
        taskService.modifyTaskFromUI(task);
        return new BaseResponseVo();
    }

    @RequestMapping(value = "/batchUpdateTask", method = RequestMethod.POST)
    public BaseResponseVo batchUpdateTask(@Validated @RequestBody BatchUpdateDto updateDto) {
        taskService.batchUpdate(updateDto.getNextRunTime(), updateDto.getStatus().getCode(), updateDto.getList());
        return new BaseResponseVo();
    }

    @RequestMapping(value = "/getTasks",method = RequestMethod.POST)
    public BaseResponseVo getTasks(@Validated @RequestBody TaskQueryReqDto taskQueryReqDto){
        TaskQueryRespDto tasks = taskService.getTasks(taskQueryReqDto);
        return new BaseResponseVo(tasks);
    }
}
